import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Avatar, 
  Card, 
  Descriptions, 
  Table, 
  Button, 
  Tag, 
  Spin, 
  Empty,
  message 
} from 'antd';
import { 
  UserOutlined, 
  DownloadOutlined, 
  ArrowLeftOutlined 
} from '@ant-design/icons';
import { fetchUserProfile, fetchUserTorrents,downloadTorrent } from '../../store/modules/userStore';
import { useDispatch } from 'react-redux';
import './UserDetailPage.css';
import { RouterAuth } from "../../router/routerAuth";

const UserDetailPage = () => {
  const { userId } = useParams();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [userInfo, setUserInfo] = useState(null);
  const [torrents, setTorrents] = useState(null); // null表示未加载，[]表示无数据
  const [loading, setLoading] = useState(true);
    const passKey = localStorage.getItem('passKey');

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      render: size => `${(size / (1024 * 1024)).toFixed(2)} MB`,
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      render: time => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button 
          type="link" 
          icon={<DownloadOutlined />}
          onClick={() => handleDownload(record.id)}
        />
      ),
    },
  ];

  // 处理下载
  const handleDownload = async (torrentId) => {
    try {
    const res = await dispatch(downloadTorrent({
      id: torrentId,
      passKey: passKey
    }));
    
    if (res.code === 0) {
      const downloadUrl = res.data;
      // 创建隐藏的a标签触发下载
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = '';
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      message.success('开始下载种子文件');
    } else {
      message.error(res.msg || '下载失败');
    }
  } catch (err) {
    console.error('下载错误:', err);
    message.error('下载失败');
  }
 
};

  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        
        // 1. 先获取用户基本信息
        const userRes = await dispatch(fetchUserProfile(userId));
        if (userRes.code !== 0) {
          throw new Error(userRes.msg || '获取用户信息失败');
        }
        setUserInfo(userRes.data);
        
        // 2. 获取用户种子列表
        const torrentsRes = await dispatch(fetchUserTorrents({ userId }));
        
        // 根据后端返回的code处理不同情况
        if (torrentsRes.code === 0) {
          // 正常返回数据
          setTorrents(torrentsRes.data?.list || []);
        } else if (torrentsRes.code === 1) {
          // 特殊code=1表示没有种子

          setTorrents([]); // 设置为空数组表示无数据
        } else {
          // 其他错误情况
          throw new Error(torrentsRes.msg || '获取种子列表失败');
        }
        
      } catch (err) {
        console.error('加载数据失败:', err);
        message.error(err.message);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [userId, dispatch]);

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!userInfo) {
    return (
      <div className="error-container">
        <Empty
          description="用户信息加载失败"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </div>
    );
  }

  return (
    <RouterAuth>
    <div className="user-detail-container">
      <Button 
        type="text" 
        icon={<ArrowLeftOutlined />}
        onClick={() => navigate(-1)}
        className="back-button"
      >
        返回
      </Button>

      <Card title="用户信息" className="user-info-card">
        <div className="user-header">
          <Avatar 
            size={64} 
            src={userInfo.avatar} 
            icon={<UserOutlined />} 
            className="user-avatar"
          />
          <h2 className="username">{userInfo.username}</h2>
        </div>
        
        <Descriptions bordered column={2}>
          <Descriptions.Item label="用户ID">{userInfo.userId}</Descriptions.Item>
          <Descriptions.Item label="等级">
            <Tag color="blue">Lv.{userInfo.level}</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="注册时间">
            {new Date(userInfo.registrationDate).toLocaleDateString()}
          </Descriptions.Item>
          <Descriptions.Item label="上传量">
            {`${(userInfo.uploadedDelta / 1024).toFixed(2)} GB`}
          </Descriptions.Item>
        </Descriptions>
      </Card>

      <Card 
        title="上传的种子" 
        className="torrents-card"
      >
        {torrents === null ? (
          <Spin tip="加载种子列表..." />
        ) : torrents.length > 0 ? (
          <Table 
            columns={columns}
            dataSource={torrents}
            rowKey="id"
            pagination={false}
            size="small"
          />
        ) : (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="该用户尚未上传任何种子"
          />
        )}
      </Card>
    </div>
    </RouterAuth>
  );
  
};

export default UserDetailPage;